<?php

namespace control;

class inStockExecClass extends adIndexClass
{
    private const power = 'inStockExec';
    private const printPage = 'inStock';
    private const page = 'inStockExec';
    private const table = 'inventory_changes';
    private const tableMx = 'inventory_changes_detail';
    private const tableRecord = 'inventory_record';
    private const title = '入库单';
    private const source = ['生产入库', '生产退料', '委外收货', '委外退料', '销售退货', '采购收货', '线边库存退库', '报废入库', '其他入库'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.inStockExec.homeListSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => '{l.inStock.homeForm.source}',
                        'width' => 200,
                    ],
                    'target'  => [
                        'name'  => '{l.inStock.homeForm.targetId}',
                        'width' => 300,

                    ],
                    'confirmTime'  => [
                        'name'  => '{l.inStock.homeSearch.completionDate}',
                        'width' => 280,
                        'sort' => 1,
                    ],
                    'text'  => [
                        'name'  => '{l.inStockExec.edit.text}',
                        'width' => 300,
                    ],
                    'state'         => [
                        'name'  => '{l.inStock.homeForm.stateSelect}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inStock.homeForm.source') => select(["name" => "type", 'option' => self::source]),
                    L('inStock.homeForm.orderNo')   => text(array("name" => "orderNo")),
                    L('inStock.homeForm.targetId')   => text(array("name" => "sourceTargetName")),
                ],
                [
                    '入库完成日期'  => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::power, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>" . L('inStockExec.homeListSearch.newPutIn') . "</span>\n";
        }
        if ($this->power(self::power, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('inStockExec.homeListSearch.del') . "</span>\n";
        }
        if ($this->power(self::power, "cancel")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'cancel'})\">" . L('inStockExec.homeListSearch.cancel') . "</span>\n";
        }
        if ($this->power(self::power, "print")) {
            $button .= " <span onclick=\"batchPrint('{$this->get('cla')}')\" class='spanButton'>" . L('inStockExec.homeListSearch.batchPrint') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::power, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if (para('CSAIII') == '是') {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'updateTime'})\">修改完成时间</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' AND classify = 1 ";
        $equal = [
            'type' => $this->post('type'),
        ];
        $like  = [
            'orderNo'          => $this->post('orderNo'),
            'sourceTargetName' => $this->post('sourceTargetName'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'confirmTime');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'CASE WHEN confirmTime IS NULL THEN 0 ELSE 1 END,CASE WHEN confirmTime IS NULL THEN time ELSE NULL END DESC,confirmTime',//  -- 将confirmTime为NULL的放在前面  -- confirmTime为NULL的情况下按照time倒序  -- 最后按照confirmTime倒序
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                        = $this->page(array(
            "table" => self::table,
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $isPrint                     = $this->power(self::power, "print");
        $checkCtrl                   = optionSettingClass::getSettingItem('库存', 'checkCtrl');// 库存是否需要复核
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            $edit = ($array['state'] == '待入库' || ($array['state'] == '已入库' && $checkCtrl));
            //列表控件
            $dominate = [
                "box"    => ["name" => "listId", "value" => $array['id'],],
                "detail" => ["title" => L('inStockExec.homeListSearch.detail'), "click" => "newIframe('" . L('inStockExec.homeListSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')",],
                "edit"   => $edit ? ["title" => L('inStockExec.homeListSearch.edit'), "click" => "newIframe('" . L('inStockExec.homeListSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')",] : [],
                'print'  => ($isPrint === true) ? ['title' => L('inStockExec.homeListSearch.print'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'target':
                        $target   = self::getCompanyName($array['targetId']);
                        $row[] = $target;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::power, 'import')) {
            $_SESSION['warn'] = L('inStockExec.importData.power');
        }  else {
            $exampleData[] = [
                '', '采购收货', '	GYS001', 'A供应商', '样例数据', '', 'YL002', 'B原料', 'CK001', 'A产品仓库', 'P0001', '默认仓位', 100, 50, '', '2023-03-16',
            ];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '单据编号'=>$example[0],
                            '业务类型'=>$example[1],
                            '往来单位编号'=>$example[2],
                            '销售合同编号'=>$example[3],
                            '单据备注'=>$example[4],
                            '待入库单号'=>$example[5],
                            '物料编码'=>$example[6],
                            '物料名称'=>$example[7],
                            '仓库编码'=>$example[8],
                            '仓库名称'=>$example[9],
                            '库位编码'=>$example[10],
                            '库位名称'=>$example[11],
                            '数量'=>$example[12],
                            '单价'=>$example[13],
                            '批次'=>$example[14],
                            '单据日期'=>$example[15],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text   = str_replace(["{{staffName}}"], [$this->control['name']], L('inStockExec.importData.importTempLog'));
            $this->logText(["type" => self::power, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::power, 'import')) {
            $json['warn'] = L('inStockExec.importData.power');
        } else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x         = 0;
            $text      = '';
            $saleOrder = [];
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    if (!empty($cell['业务类型'])) {
                        $saleOrder   = [];
                        $companyInfo = query('kehu', "orderNo = '$cell[往来单位编号]' and coid = '" . self::$coid . "' ", " khid as id,concat(orderNo,'-',companyName) as name ");
                        if (empty($companyInfo['id'])) {
                            $companyInfo = query('supplier', "code = '$cell[往来单位编号]' and coid = '" . self::$coid . "'", " id,concat(code,'-',name) as name ");
                        }
                        $field      = [
                            'type'       => $cell['业务类型'],
                            'targetId'   => $companyInfo['id'],
                            'recordDate' => self::importDateFormat($cell['单据日期']),
                            'text'       => $cell['单据备注'],
                        ];
                        $annotation = [
                            'type'     => L('inStockExec.editEdit.type'),
                            'targetId' => L('inStockExec.editEdit.type'),
                            'text'     => L('inStockExec.editEdit.text'),
                        ];
                        $rules      = [
                            'type' => 'required',
                        ];
                        $info       = query(self::table, "classify = 1 and orderNo = '$cell[单据编号]' and coid = '" . self::$coid . "'");
                        // 校验是否符合规则
                        $vt     = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                        } elseif (!in_array($field['type'], self::source)) {
                            $text .= "\n第【{$row_list}】行，" . L('inStockExec.editEdit.importWarnOne');
                        } elseif (!empty($info['id']) && $info['state'] != '待入库') {
                            $text .= "\n第【{$row_list}】行，" . L('inStockExec.editEdit.importWarnTwo');
                        } else {
                            if (empty($info['id'])) {
                                // 新增
                                $userNo = codeTemplateClass::generateCode(self::power, [
                                    'prefix' => 'RKD' . date('Ymd', strtotime($field['recordDate'])),
                                    'table'  => self::table,
                                    'field'  => 'orderNo',
                                    'where'  => " AND coid = '" . self::$coid . "' ",
                                ], $field);
                                $field  = array_merge($field, [
                                    'id'               => suiji(),
                                    'orderNo'          => $userNo,
                                    'classify'         => 1,
                                    'sourceTargetName' => $companyInfo['name'],
                                    'state'            => '待入库',
                                    'coid'             => self::$coid,
                                    'stid'             => $this->control['stid'],
                                    'time'             => $field['recordDate'] ?: $this->time,
                                ]);
                                $warn   = static::insert([
                                    "table" => self::table,
                                    "field" => $field,
                                ]);
                            } else {
                                $warn = static::update([
                                    "table" => self::table,
                                    "field" => $field,
                                    'where' => "id = '$info[id]'",
                                ]);
                            }
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $saleOrder = match ($warn) {
                                    '新增成功' => $field,
                                    default => $info
                                };
                            } else {
                                $text .= "\n第【{$row_list}】行，编辑主数据失败，" . $warn;
                            }
                        }
                    }
                    if (isset($saleOrder['id']) && !empty($saleOrder['id'])) {
                        $material  = query('material', "coid = '" . self::$coid . "' and code = '$cell[物料编码]'");
                        $warehouse = query('warehouse', "orderNo = '$cell[仓库编码]' and coid = '" . self::$coid . "'");
                        if (empty($material['id'])) {
                            $text .= "\n第【{$row_list}】行，物料不存在";
                            continue;
                        } elseif (empty($warehouse['id'])) {
                            $text .= "\n第【{$row_list}】行，仓库不存在";
                            continue;
                        }
                        //库位匹配
                        if ($cell['库位编码']) {
                            $positionId = query("warehouse_position", " orderId = '" . $warehouse['id'] . "' and code = '$cell[库位编码]' ", 'id')['id'];
                        } else {
                            $positionId = inventoryBalanceClass::matchLocation($warehouse['id']);
                        }
                        if (empty($positionId)) {
                            $text .= "\n第【{$row_list}】行，库位不存在或默认库位不存在";
                            continue;
                        }
                        $mx        = query(self::tableMx, "materialId = '$material[id]' and orderId = '$saleOrder[id]' and sourceNo = '$cell[待入库单号]' and batch = '$cell[批次]'");
                        $cell['数量']  = self::formattingFigure($cell['数量'], 'numPrecision');
                        $price     = $cell['单价'] ? self::formattingFigure($cell['单价'], 'pricePrecision') : $material['buyPrice'];
                        $orderNum  = 0;
                        $sourceNo  = "";
                        $inventory = query('inventory', "coid = '" . self::$coid . "' and orderNo = '$cell[待入库单号]'");
                        if (!empty($inventory['id'])) {
                            $inventory_detail = query('inventory_detail', "orderId = '$inventory[id]' and materialId = '$material[id]'");
                            $orderNum         = $inventory_detail['orderNum'];
                            $sourceNo         = $inventory['orderNo'];
                            $price            = $inventory_detail['price'];
                        }
                        if (empty($mx['id'])) {
                            //明细
                            $mxField = [
                                'id'          => suiji(),
                                'coid'        => self::$coid,
                                'orderId'     => $saleOrder['id'],
                                'materialId'  => $material['id'],
                                'orderNum'    => $orderNum,
                                'batch'       => $cell['批次'],
                                'num'         => $cell['数量'],
                                'unit'        => $inventory_detail['unit'] ?? $material['unit'],
                                'price'       => $price,
                                'money'       => self::formattingFigure($price * $cell['数量']),
                                'warehouseId' => $warehouse['id'],
                                'positionId'  => $positionId,
                                'sourceTable' => isset($inventory_detail['id']) ? 'inventory_detail' : '',
                                'sourceId'    => $inventory_detail['id'] ?? '',
                                'sourceNo'    => $sourceNo,
                            ];
                            $warn    = static::insert([
                                "table" => self::tableMx,
                                "field" => $mxField,
                            ]);
                        } else {
                            //明细
                            $mxField = [
                                'materialId'  => $material['id'],
                                'orderNum'    => $orderNum,
                                'batch'       => $cell['批次'],
                                'num'         => $cell['数量'],
                                'unit'        => $inventory_detail['unit'] ?? $material['unit'],
                                'price'       => $price,
                                'money'       => self::formattingFigure($price * $cell['数量']),
                                'warehouseId' => $warehouse['id'],
                                'positionId'  => $positionId,
                                'sourceTable' => isset($inventory_detail['id']) ? 'inventory_detail' : '',
                                'sourceId'    => $inventory_detail['id'] ?? '',
                                'sourceNo'    => $sourceNo,
                            ];
                            $warn    = static::update([
                                "table" => self::tableMx,
                                "field" => $mxField,
                                'where' => "id = '$mx[id]'",
                            ]);
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $text .= "\n第【{$row_list}】行，导入成功";
                            $x++;
                        } else {
                            $text .= "\n第【{$row_list}】行，导入失败：插入数据库失败，" . $warn;
                        }
                    } else {
                        $text .= "\n第【{$row_list}】行，未找到单据";
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::power, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::power, 'export')) {
            $_SESSION['warn'] = L('inStockExec.exportData.power');
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by CASE WHEN confirmTime IS NULL THEN 0 ELSE 1 END,CASE WHEN confirmTime IS NULL THEN time ELSE NULL END DESC,confirmTime desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $target = self::getCompanyName($array['targetId']);
                $mx     = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]' order by list"));
                foreach ($mx['array'] as $value) {
                    $material  = query('material', " id = '$value[materialId]'");
                    $warehouse = query('warehouse', " id = '$value[warehouseId]' ", 'name');
                    $position  = query('warehouse_position', " id = '$value[positionId]' ", 'name');
                    if ($value['sourceId']) {
                        $putIn = find(array('table' => self::tableRecord, 'single' => "inventoryMxId = '$value[sourceId]'", 'field' => " IFNULL(sum(num),0) as num "));
                        $price = '-';
                    } else {
                        $putIn['num'] = 0;
                        $price        = self::lostZero($value['price'], 'pricePrecision');
                    }
                    foreach ($tempFieldAll as $templateField) {
                        if ($templateField['display']) {
                            $column[] = match ($templateField['columnName']) {
                                '单据编号' => $array['orderNo'],
                                '业务类型' => $array['type'],
                                '往来单位' => $target,
                                '入库完成时间' => $array['confirmTime'],
                                '状态' => $array['state'],
                                '待入库单号' => $value['sourceNo'],
                                '物料编码' => $material['code'],
                                '物料名称' => $material['name'],
                                '规格型号' =>  $material['model'],
                                '单位' => $value['unit'],
                                '仓库' =>   $warehouse['name'],
                                '库位' =>$position['name'],
                                '单据数量' => self::lostZero($value['orderNum'], 'numPrecision'),
                                '已入库数量' =>self::lostZero($putIn['num'], 'numPrecision'),
                                '本次入库数量' =>self::lostZero($value['num'], 'numPrecision'),
                                '单价' => $price,
                                '批号' => $value['batch'],
                                default => '',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inStockExec.exportData.log'));
            $this->logText(["type" => self::printPage, "text" => $text]);
            $this->excelOut($title, $data, L('inStockExec.exportData.fileName') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => L('inStockExec.edit.save'),
            "type"  => "点击事件",
            "title" => L('inStockExec.edit.save'),
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $tr[]     = ['', '{l.inStockExec.edit.sourceNo}', '{l.inStockExec.edit.code}', '{l.inStockExec.edit.name}', '{l.inStockExec.edit.model}', '{l.inStockExec.edit.unit}',  '<div class="warehouse">' . '{l.inStockExec.edit.warehouse}' . self::chooseWarehouse(callback: 'getPosition') . '</div>', '入库数量','磅差',  '{l.inStockExec.edit.price}', '{l.feeApply.home.money}', '{l.inStockExec.edit.batch}'];
        $numTotal = $moneyTotal =$numDataTotal = 0;
        // 来源待入库单
        if ($this->get('ids')) {
            $target = query("inventory", " id = '" . $this->get('targetId') . "' ");
            //主表信息
            $info['type']             = $target['type'];
            $info['targetId']         = $target['targetId'];
            $info['sourceTargetName'] = self::getCompanyName($target['targetId']);

            $mxIdArr = array_filter(explode('/', $this->get('ids')));
            //是否自动生成批号
            //物料档案管理批号，并且公共设置批号自动生成，并且自动带出批号
            $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
            $batchCtrl     = $optionSetting['batchCtrl'];
            foreach ($mxIdArr as $k=>$detailId) {
                $inventory_detail             = query("inventory_detail", " id = '" . $detailId . "' ");
                // 如果入库前需要先完成质检，并且是待质检，则不能入库
                if(optionSettingClass::getSettingItem('库存', 'inStockQuality') && $inventory_detail['quality'] == 1){
                    continue;
                }
                $inventory                    = query("inventory", " id = '" . $inventory_detail['orderId'] . "' ", "orderNo");
                $material                     = query('material', "id = '$inventory_detail[materialId]'");
                $batch                        = $inventory_detail['batch'] ?: (($batchCtrl['option'] && $batchCtrl['auto']) ? inStockClass::getBatchNo($info['type'], $info['targetId']) : '');
                $id                           = self::getId();
                $warehouseSel                 = idSelect(array(
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql().' order by time asc',
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'title'    => '仓库',
                    'change'   => 'getPosition',
                    'value'    => $inventory_detail['warehouseId']
                ));
                $position                     = selectMultiple([
                        "name"     => "positionId[]",
                        'table'    => "warehouse_position",
                        'where'    => "coid = '" . self::$coid . "' and orderId = '" . $inventory_detail['warehouseId'] . "' and state = '启用' order by list",
                        'sqlId'    => 'id',
                        'sqlField' => 'name',
                        'title'    => L('inStockExec.edit.position'),
                        'value'    => $inventory_detail['positionId'] ?: ($inventory_detail['warehouseId'] ? inventoryBalanceClass::matchLocation($inventory_detail['warehouseId']) : '')]
                );
                $putIn                        = find(array(
                    'table'  => self::tableRecord,
                    'single' => "inventoryMxId = '$inventory_detail[id]'",
                    'field'  => " IFNULL(sum(num),0) as num "
                ));
                $notIn                        = $inventory_detail['orderNum'] - $putIn['num'];
                if($inventory_detail['orderNum'] == 0){
                    $notIn = $inventory_detail['num'] - $putIn['num'];
                }
                $inventory_detail['orderNum'] = self::lostZero($inventory_detail['orderNum'], 'numPrecision');
                $putIn['num']                 = self::lostZero($putIn['num'], 'numPrecision');
                $money                        = self::formattingFigure($notIn * $inventory_detail['price']);
                $tr[]                         =
                    [
                        componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $material['id']]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => 'inventory_detail']) .
                        hidden(['name' => 'sourceId[]', 'value' => $detailId]),
                        $inventory['orderNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
//                        self::lostZero($inventory_detail['orderNum'], 'numPrecision'),
//                        self::lostZero($putIn['num'], 'numPrecision'),
                    $warehouseSel,
//                        "<span class='position'>{$position}</span>",
//                    readOnlyInput(array("name" => "num[]", "value" => self::lostZero($notIn, 'getNum'))),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'getNum', 'value' => self::lostZero($notIn, 'numPrecision'))).hidden(['name'=>'orderNum[]','value'=>$inventory_detail['orderNum']]),
                    text(['name'=>'getNum[]','value'=>0]),
                    readOnlyInput(array("name" => "price[]", "value" => $inventory_detail['price'])),
                    readOnlyInput(array("name" => "money[]", "value" => $money)),
                    text(['name' => 'batch[]', 'value' => $batch]),
                ];
                $numTotal                     += $notIn;
                $moneyTotal                   += $money;
                $numDataTotal += 0;
            }
        } else {
            $inventorySetting = optionSettingClass::getSetting('库存');
            $checkCtrl        = $inventorySetting['checkCtrl'];// 库存是否需要复核
            $result           = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ((array)$result['array'] as $k=>$array) {
                $material = query('material', " id = '$array[materialId]'");
                $putIn    = $array['sourceId'] ?
                    self::lostZero(find(array(
                        'table'  => self::tableRecord,
                        'single' => "inventoryMxId = '$array[sourceId]' and inventoryMxId !=''",
                        'field'  => " IFNULL(sum(num),0) as num "
                    ))['num'], 'numPrecision') : '';
                //待入库可编辑
                if ($info['state'] == '待入库') {
                    $del       = componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal();");
                    $warehouse = idSelect(array(
                        'name'     => 'warehouseId[]',
                        'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' and state = '启用' " . self::getWarehouseSql(),
                        'sqlId'    => 'id',
                        'sqlField' => "name",
                        'change'   => 'getPosition',
                        'title'    => '仓库',
                        'value'    => $array['warehouseId']
                    ));
                    $position  = selectMultiple([
                        "name"     => "positionId[]",
                        'table'    => "warehouse_position",
                        'where'    => "coid = '" . self::$coid . "' and orderId = '" . $array['warehouseId'] . "' and state = '启用' order by list",
                        'sqlId'    => 'id',
                        'sqlField' => 'name',
                        'value'    => $array['positionId'],
                        'title'    => L('inStockExec.edit.position')
                    ]);
                    $batch     = text(['name' => 'batch[]', 'value' => $array['batch']]);
                    $price     = empty($array['sourceId']) ?
                        text(['name' => 'price[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'), 'other' => self::digitalFiltering('pricePrecision')]) :
                        readOnlyInput(array("name" => "price[]", "value" => self::lostZero($array['price'], 'pricePrecision')));
                    $money     = empty($array['sourceId']) ?
                        text(['name' => 'money[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['money']), 'other' => self::digitalFiltering()]) :
                        readOnlyInput(array("name" => "money[]", "value" => self::lostZero($array['money'])));
                } else {
                    $del       = componentClass::tablePperation($k+1,"");
                    $warehouse          = query("warehouse", " id = '" . $array['warehouseId'] . "' ", "name");
                    $warehouse_position = query("warehouse_position", " id = '" . $array['positionId'] . "' ", "name");
                    $warehouse          = $warehouse['name'] . hidden(array("name" => "warehouseId[]", "value" => $array['warehouseId']));
                    $position           = $warehouse_position['name'] . hidden(array("name" => "positionId[]", "value" => $array['positionId']));
                    $batch              = readOnlyInput(array("name" => "batch[]", "value" => $array['batch']));
                    $price              = readOnlyInput(array("name" => "price[]", "value" => self::lostZero($array['price'], 'pricePrecision')));
                    $money              = readOnlyInput(array("name" => "money[]", "value" => self::lostZero($array['money'])));
                }
                $num        = ($info['state'] == '待入库' || ($info['state'] == '已入库' && $checkCtrl)) ?
                    text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['num'], 'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]) :
                    self::lostZero($array['num'], 'numPrecision');
                $tr[]       =
                    [
                        $del .
                        hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                        hidden(['name' => 'materialId[]', 'value' => $array['materialId']]) .
                        hidden(['name' => 'unit[]', 'value' => $array['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => $array['sourceTable']]) .
                        hidden(['name' => 'sourceId[]', 'value' => $array['sourceId']]),
                        $array['sourceNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $array['unit'],
//                        $array['sourceId'] ? self::lostZero($array['orderNum'], 'numPrecision') : '',
//                        $putIn,
                    $warehouse,
                    "<span class='position'>{$position}</span>",
                    $num,
                    $array['sourceId'] ? $array['orderNum'] - $num : 0,
                    $price,
                    $money,
                    $batch,
                ];
                $numTotal   += $array['num'];
                $moneyTotal += $array['money'];
                $numDataTotal += $array['sourceId'] ? $array['orderNum'] - $num : 0;
            }
        }
        $total_tr = [
            7 => "<span class='numTotal'>".self::lostZero($numTotal, 'numPrecision')."</span>",
            8 => "<span class='numTotal'>".self::lostZero($numDataTotal, 'numPrecision')."</span>",
            10 => "<span class='moneyTotal'>" . self::lostZero($moneyTotal) . "</span>",
        ];
        $table = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total_tr));
        $page = self::page;
        $but  = '';
        if (!$info['state'] || $info['state'] == '待入库') {
            $but = "<span class='smallButton' onclick='chooseWait()'>" . L('inStockExec.edit.choiceNotIn') . "</span>
                    <span class='smallButton' onclick=\"layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())\">" . L('inStockExec.edit.choiceMaterial') . "</span>";
        }
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('inStockExec.edit.source') => selectMultiple([
                        'option' => self::source,
                        "title"  => L('inStockExec.edit.choice'),
                        'name'   => 'type',
                        'value'  => $info['type']
                    ]),
                    L('inStockExec.edit.target')        => text(array(
                            'name'  => 'sourceTargetName',
                            'id'    => 'target',
                            'value' => $info['sourceTargetName']
                        )) .
                        hidden(array('name' => 'targetId', 'value' => $info['targetId'])) .
                        "<span class='del-row-button' onclick=\"newIframe('客户档案','" . root . "control/adIndex.html?cla=clientProfile&fun=edit')\" >新建客户</span>&nbsp;&nbsp;&nbsp;" .
                        "<span class='del-row-button' onclick=\"newIframe('供应商详情','" . root . "control/adIndex.html?cla=supplier&fun=edit')\" >新建供应商</span>",
                    L('inStock.homeSearch.startTime') => text(['name' => "recordDate", 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date]),
                ],
                [
                    L('inStockExec.edit.text')        => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('inStockExec.edit.inMx'),
            'button' => $but,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
$("#target").bigAutocomplete({
        url:root + 'control/adIndex.html?cla={$this->get('cla')}&fun=getTarget',
        callback:function(data){
            $("[name='targetId']").val(data.id);
        }
    });
function getNum(that) {
  let num = $(that).val(),orderNum = $(that).siblings().val();
      let par = $(that).parent().parent()
    let priceNode = par.find("[name='getNum[]']")
    let numData = Math.round((orderNum*1 - num*1) * 1000) / 1000
priceNode.val(numData);
  
}
function addRow(type=''){
    if(type == 'addWaitPutIn'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addWaitPutInEdit',$("form[name='orderForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            calculateTotal()
            resetNumber($("#materialTable"))
        },'json');
    }else{
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
        },'json');
    }
}
function chooseWait() {
    layer('{$this->get('cla')}','addWaitPutIn',$('form[name=inStockExecEditForm]').serialize())
}
function countMoney(e) {
    let currentKey = $(e).attr('name')
    let par = $(e).parent().parent()
    let numNode = par.find("[name='num[]']")
    let priceNode = par.find("[name='price[]']")
    let moneyNode = par.find("[name='money[]']")
    let num = numNode.val()*1
    let price = priceNode.val()*1
    let money = moneyNode.val()*1
    if(currentKey === 'num[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'price[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'money[]'){
        if(num > 0){
            priceNode.val((money / num).toFixed(publicSettings.pricePrecision.num)).trigger('input')
        }else if(price > 0){
            numNode.val((money / price).toFixed(publicSettings.numPrecision.num))
        }
    }
    calculateTotal()
}
//计算总金额，总税额
function calculateTotal(){
    let num = 0,
    money = 0;
    $(".editList").find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var moneyValue = $(".editList").find("[name='money[]']").eq(index).val()
        if(moneyValue){
            money+=Number(moneyValue);
        }
    })
    $(".numTotal").text(num.toFixed(publicSettings.numPrecision.num));
    $(".moneyTotal").text(money.toFixed(amountPrecision));
}
//根据仓库获取库位
function getPosition(e){
    let warehouseId = e.value;
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getPosition',{warehouseId:warehouseId},function(res) {
          $(e).parent().parent().find(".position").html(res.position);
    },'json');
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /** 根据仓库获取库位
     * @param string $warehouseId
     * @return mixed
     */
    public function getPosition($warehouseId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $position    = query('warehouse_position', "orderId = '$warehouseId' and isDefault = 1");
        //批号
        $json['position'] = selectMultiple([
            "name"     => "positionId[]",
            'value'    => $position['id'],
            'table'    => "warehouse_position",
            'where'    => "coid = '" . self::$coid . "' and orderId = '" . $warehouseId . "' and state = '启用' order by list",
            'sqlId'    => 'id',
            'sqlField' => 'name',
            'title'    => L('inStockExec.edit.position')
        ]);
        return json_encode($json, 320);
    }

    /**
     * 模糊查询往来单位
     *
     * @return bool|string
     */
    public function getTarget(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $json['data'] = [];
        $where        = $where2 = '';
        if (!empty($val)) {
            $where  = " and (companyName like '%" . $val . "%' or orderNo like '%" . $val . "%')";
            $where2 = " and (name like '%" . $val . "%' or code like '%" . $val . "%')";
        }
        $res = self::sqlFind(" select khid as id,concat(orderNo,'-',companyName) as name from kehu where coid = '" . self::$coid . "' {$where} UNION ALL select id,concat(code,'-',name) as name from supplier where coid = '" . self::$coid . "' {$where2} ");
        foreach ($res as $val) {
            $json['data'][] = array(
                'title' => $val['name'],
                'id'    => $val['id'],
            );
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 获取往来单位
     *
     * @return array
     */
    final public static function currentCompany(): array
    {
        $res = self::sqlFind(" select khid as id,concat(orderNo,'-',companyName) as name from kehu where coid = '" . self::$coid . "' UNION ALL select id,concat(code,'-',name) as name from supplier where coid = '" . self::$coid . "' ");
        return array_column($res, 'name', 'id');
    }

    /**获取往来单位名称
     *
     * @param string $targetId
     * @return string
     */
    final public static function getCompanyName($targetId = ''): string
    {
        $target = '';
        if ($targetId) {
            $target = query('kehu', " khid = '$targetId' ")['companyName'];
            if (empty($target)) {
                $target = query('supplier', " id = '$targetId' ")['name'];
            }
        }
        return $target;
    }


    /**
     * 选择仓库
     *
     * @return string
     */
    public static function chooseWarehouse(string $obj = '', string $callback = ''): string
    {
        $obj    = $obj ?: 'warehouseId';
        $result = find(array(
            'table' => 'warehouse',
            'where' => " coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql() . " order by time desc"
        ));
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>" . L('inStockExec.chooseWarehouse.none') . "</li>";
        }
        $batch = L('inStockExec.chooseWarehouse.batch');
        return <<<EOT
        <span class='del-row-button' id='chooseWareHouse'>{$batch}</span><div class='stateBlock' style="margin-top: 7px;"><ul>$li</ul></div>
        <script>
         //点击非下拉区域隐藏
        $(document).bind('click', function (e) {
            let target = $(".stateBlock");
            let obj = $(".warehouse");
            if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
              target.hide();
            }
        });
        $("#chooseWareHouse").on('click',function() {
           $(".stateBlock").show();
        })
        $(".warehouse .stateBlock li").on('click',function() {
            let id = $(this).data('id');
            $("select[name='{$obj}[]']").each(function() {
              let obj = $(this);
              obj.val(id);
              $callback(this)
            });
           $(".stateBlock").hide();
        })
        </script>    
EOT;
    }

    public function editEdit()
    {
        $id             = $this->post('id') ?: self::getId();
        $mxIdArr        = $this->post('mxId') ?: [];
        $materialIdArr  = $this->post('materialId');
        $unitArr        = $this->post('unit');
        $warehouseArr   = $this->post('warehouseId');
        $positionIdArr  = $this->post('positionId');
        $numArr         = $this->post('num');
        $priceArr       = $this->post('price');
        $batchArr       = $this->post('batch');
        $sourceTableArr = $this->post('sourceTable');
        $sourceIdArr    = $this->post('sourceId');

        $field      = [
            'type'             => $this->post('type'),
            'sourceTargetName' => $this->post('sourceTargetName'),
            'targetId'         => $this->post('targetId'),
            'recordDate'       => $this->post('recordDate'),
            'text'             => $this->post('text'),
        ];
        $annotation = [
            'type'     => L('inStockExec.editEdit.type'),
            'targetId' => L('inStockExec.editEdit.type'),
            'text'     => L('inStockExec.editEdit.text'),
        ];
        $rules      = [
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where     = " id = '$id' ";
        $info      = query(self::table, $where);
        $checkCtrl = optionSettingClass::getSettingItem('库存', 'checkCtrl');// 库存是否需要复核
        //判断
        if (!$this->power(self::power, "edit")) {
            $json['warn'] = L('inStockExec.editEdit.power');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('inStockExec.editEdit.notMx');
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = L('inStockExec.editEdit.notMx');
        } elseif (static::is_null_array($warehouseArr)) {
            $json['warn'] = L('inStockExec.editEdit.notWarehouse');
        }  elseif (static::is_null_array($numArr, false)) {
            $json['warn'] = L('inStockExec.editEdit.quantityMissing') . '，且不能为0';
        } elseif (!empty($info['id']) && (in_array($info['state'], ['已复核', '已作废']) || (!$checkCtrl && $info['state'] == '已入库'))) {
            $json['warn'] = L('inStockExec.editEdit.cannotModified');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            //更新基础数据
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(self::power, [
                    'prefix' => 'RKD' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ], $field);
                $field        = array_merge($field, [
                    'id'       => $id,
                    'orderNo'  => $orderNo,
                    'classify' => 1,
                    'state'    => '待入库',
                    'coid'     => self::$coid,
                    'stid'     => $this->control['stid'],
                    'time'     => $this->post('recordDate') ?: $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx = query(self::tableMx, "id = '$nid'");
                    //获取源单数据
                    $orderNum = 0;
                    $sourceNo = "";
                    $price    = $priceArr[$k] ?: 0;
                    if (!empty($sourceIdArr[$k])) {
                        $source    = query($sourceTableArr[$k], "id = '$sourceIdArr[$k]'");
                        $inventory = query("inventory", "id = '$source[orderId]'");
                        $orderNum  = $source['orderNum'];
                        $sourceNo  = $inventory['orderNo'];
                        $price     = $source['price'];  //采购入库价
                    }
                    $price      = self::formattingFigure($price, 'pricePrecision');
                    $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'warehouseId' => $warehouseArr[$k],
                                'positionId'  => '',
                                'num'         => $numArr[$k],
                                'price'       => $price,
                                'batch'       => $batchArr[$k],
                                'money'       => self::formattingFigure($price * $numArr[$k]),
                            ],
                            "where" => " id = '$nid'",
                        ]);
                        //未复核前可以修改入库数量
                        if ($info['state'] == '已入库') {
                            // 转换主单位
                            $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $numArr[$k], $mx['unit']);
                            static::update([
                                "table" => self::tableRecord,
                                "field" => [
                                    'num' => $mainUnitNum,
                                ],
                                "where" => " changesId = '$nid' and coid = '" . self::$coid . "' ",
                            ]);
                            if (!empty($sourceIdArr[$k])) {
                                //修改线边库存
                                static::update([
                                    "table" => 'line_inventory',
                                    "field" => [
                                        'num' => -$mainUnitNum,
                                    ],
                                    "where" => " changesId = '$nid' and coid = '" . self::$coid . "' ",
                                ]);
                                //更新账户变动记录
                                $money  = round($numArr[$k] * $source['price'] * (1 + $source['rate']), 2);
                                $record = find(array(
                                    'table'  => 'record',
                                    'single' => " changesId = '$nid' and coid = '" . self::$coid . "' ",
                                    'field'  => " IFNULL(sum(money),0) as total "
                                ));
                                $total  = abs($record['total']);
                                // 关联表
                                $targetDate = $inventory['orderDate'] ?: date("Y-m-d h:i:s");
                                $targetNo   = $targetText = $hiddenText = ' ';
                                if ($inventory['sourceTable']) {
                                    $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                    if (!empty($obj['id'])) {
                                        $targetDate = $obj['recordDate'] ?: date("Y-m-d h:i:s");
                                        $targetNo   = $obj['orderNo'];
                                        $targetText = $inventory['type'] . "单号【{$obj['orderNo']}】";
                                        $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，入库单ID：' . $source['orderId'] . '入库单子ID：' . $source['id'];
                                    }
                                }
                                if ($record['total'] < 0) {
                                    $changeMoney = $money > $total ? $money - $total : -($total - $money);
                                } else {
                                    $changeMoney = $money - $total;
                                }
                                $bool = supplierClass::insertRecord(
                                    $inventory['targetId'],
                                    $inventory['type'],
                                    $changeMoney,
                                    'inventory_detail',
                                    $source['id'],
                                    $targetDate,
                                    $targetNo,
                                    $targetText,
                                    $hiddenText,
                                    $nid
                                );
                                if ($bool !== true) {
                                    $json['warn'] = L('inStockExec.editEdit.fail');
                                    goto resp;
                                }
                                //修改源单入库状态
                                $inNum = $source['num'] - $mx['num'] + $numArr[$k];
                                static::update([
                                    'table' => 'inventory_detail',
                                    'field' => [
                                        'num' => $inNum,
                                    ],
                                    'where' => " id = '{$source['id']}' ",
                                ]);
                                $notIn = find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and num < orderNum and coid = '" . self::$coid . "' and id <> '" . $source['id'] . "'",
                                    'field'  => " IFNULL(count(id),0) as num "
                                ));
                                if ($inNum >= $source['orderNum'] && $notIn['num'] == 0) {
                                    static::update([
                                        'table' => 'inventory',
                                        'field' => [
                                            'state'       => '已入库',
                                            'confirmTime' => $info['confirmTime'],
                                        ],
                                        'where' => " id = '{$inventory['id']}' ",
                                    ]);
                                } elseif ($inventory['state'] != '部分入库') {
                                    static::update([
                                        'table' => 'inventory',
                                        'field' => [
                                            'state'      => '部分入库',
                                            'commitTime' => $this->time,
                                        ],
                                        'where' => " id = '{$inventory['id']}' ",
                                    ]);
                                }
                            }
                        }
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'          => $nid,
                                'coid'        => self::$coid,
                                'orderId'     => $id,
                                'materialId'  => $materialIdArr[$k],
                                'orderNum'    => $orderNum,
                                'batch'       => $batchArr[$k],
                                'num'         => $numArr[$k],
                                'unit'        => $unitArr[$k],
                                'price'       => $price,
                                'money'       => self::formattingFigure($price * $numArr[$k]),
                                'warehouseId' => $warehouseArr[$k],
                                'positionId'  => '',
                                'sourceTable' => $sourceTableArr[$k],
                                'sourceId'    => $sourceIdArr[$k],
                                'sourceNo'    => $sourceNo,
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('inStockExec.editEdit.log'));
                $this->logText(["type" => self::printPage, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . static::page . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 批量作废
     *
     * @return bool|string
     */
    public function cancelEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::power, "cancel")) {
            $json['warn'] = L('inStockExec.cancel.power');
        } elseif (empty($array)) {
            $json['warn'] = L('inStockExec.cancel.none');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] != '已入库') {
                    $warn = L('inStockExec.cancel.fail');
                } else {
                    $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                    foreach ($result['array'] as $k => $mx) {
                        // 转换主单位
                        $mainUnitNum = 0;
                        //未复核前可以修改入库数量
                        $warn = static::update([
                            "table" => self::tableRecord,
                            "field" => [
                                'num' => $mainUnitNum,
                            ],
                            "where" => " changesId = '" . $mx['id'] . "' and coid = '" . self::$coid . "' ",
                        ]);
                        //有关联入库单，并且单据数量不是0
                        if (!empty($mx['sourceId']) && $mx['num'] != 0) {
                            $source    = query($mx['sourceTable'], "id = '" . $mx['sourceId'] . "'");
                            $inventory = query("inventory", "id = '$source[orderId]'");
                            //修改线边库存
                            static::update([
                                "table" => 'line_inventory',
                                "field" => [
                                    'num' => $mainUnitNum,
                                ],
                                "where" => " changesId = '" . $mx['id'] . "' and coid = '" . self::$coid . "' ",
                            ]);
                            //更新账户变动记录
                            $money  = 0;
                            $record = find(array(
                                'table'  => 'record',
                                'single' => " changesId = '" . $mx['id'] . "' and coid = '" . self::$coid . "' ",
                                'field'  => " IFNULL(sum(money),0) as total "
                            ));
                            $total  = abs($record['total']);
                            // 关联表
                            $targetDate = $inventory['orderDate'];
                            $targetNo   = $targetText = $hiddenText = ' ';
                            if ($inventory['sourceTable']) {
                                $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                if (!empty($obj['id'])) {
                                    $targetDate = $obj['recordDate'];
                                    $targetNo   = $obj['orderNo'];
                                    $targetText = $inventory['type'] . "单号【{$obj['orderNo']}】";
                                    $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，入库单ID：' . $source['orderId'] . '入库单子ID：' . $source['id'];
                                }
                            }
                            if ($record['total'] < 0) {
                                $changeMoney = $money > $total ? $money - $total : -($total - $money);
                            } else {
                                $changeMoney = $money - $total;
                            }
                            $bool = supplierClass::insertRecord(
                                $inventory['targetId'],
                                $inventory['type'],
                                $changeMoney,
                                'inventory_detail',
                                $source['id'],
                                $targetDate,
                                $targetNo,
                                $targetText,
                                $hiddenText,
                                $mx['id']
                            );
                            if ($bool !== true) {
                                $warn = L('inStockExec.editEdit.fail');
                                goto resp;
                            }
                            //修改源单入库状态
                            $inNum = $source['num'] - $mx['num'];
                            static::update([
                                'table' => 'inventory_detail',
                                'field' => [
                                    'num' => $inNum,
                                ],
                                'where' => " id = '{$source['id']}' ",
                            ]);
                            $inventoryState = '';
                            if (find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and num = 0 and coid = '" . self::$coid . "'",
                                    'field'  => " IFNULL(count(id),0) as num "
                                ))['num'] == find(array(
                                    'table'  => 'inventory_detail',
                                    'single' => "orderId = '$inventory[id]' and coid = '" . self::$coid . "'",
                                    'field'  => " IFNULL(count(id),0) as num "
                                ))['num']) {
                                $inventoryState = '待入库';
                            } elseif ($inventory['state'] != '部分入库') {
                                $inventoryState = '部分入库';
                            }
                            if ($inventoryState) {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'      => $inventoryState,
                                        'commitTime' => $this->time,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            }
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            goto resp;
                        }
                    }
                    static::update([
                        'table' => self::table,
                        'field' => [
                            'state' => '已作废',
                        ],
                        'where' => " id = '{$id}' ",
                    ]);
                    //返回
                    $warn = L('inStockExec.cancel.success');
                    $x++;
                }
                resp:
                $text .= str_replace(['{{id}}'], [$info['id']], lang('inStockExec.cancel.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inStockExec.cancel.log')) . "<br>" . $text;
            $this->logText(array("type" => self::printPage, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('inStockExec.cancel.warn'));
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 关联待入库单
     *
     * @return bool|string
     */
    public function addWaitPutIn(): bool|string
    {
        $html   =
            text(array("name" => "orderNo", "title" => "{l.inStockExec.addWaitPutIn.orderNo}")) .
            text(array("name" => "code", "title" => "{l.inStockExec.addWaitPutIn.code}")) .
            text(array("name" => "materialName", "title" => "{l.inStockExec.addWaitPutIn.materialName}")) .
            text(array("name" => "model", "title" => "{l.inStockExec.addWaitPutIn.model}")) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"addRow('addWaitPutIn')\" type='button' class='searchSub' value='" . L('inStockExec.addWaitPutIn.continueAdding') . "'>";
        $button .= "<input style='margin-left: 5px' onclick=\"addRow('addWaitPutIn');$('#" . self::page . "AddWaitPutIn').remove()\" type='button' class='searchSub' value='" . L('inStockExec.addWaitPutIn.sub') . "'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => L('inStockExec.addWaitPutIn.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联待入库单
     *
     * @return bool|string
     */
    public function addWaitPutInSearch(): bool|string
    {
        $where = " main.coid='" . self::$coid . "' and main.state <> '已入库' ";
        $and   = "";
        $like  = [
            'main.orderNo' => $this->post('orderNo'),
            'mat.code'     => $this->post('code'),
            'mat.name'     => $this->post('materialName'),
            'mat.model'    => $this->post('model'),
        ];
        $equal = [
            'main.type'     => $this->post('type'),
            'main.classify' => 1,
        ];
        if ($this->post('targetId')) {
            //交货日期
            $and .= " and main.targetId = '" . $this->post('targetId') . "' ";
        }
        // 入库前是否需要先完成质检
        if(optionSettingClass::getSettingItem('库存', 'inStockQuality')){
            $and .= " and mx.quality <> 1 ";
        }
        $and   .= " and orderNum - (select IFNULL(sum(num),0) as num from inventory_record where inventoryMxId = mx.id and num > 0) > 0 ";
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page([
            "table"   => "inventory_detail as mx join inventory as main on mx.orderId = main.id join material as mat on mx.materialId = mat.id",
            "field"   => "mx.id,mx.orderNum,main.orderNo,mat.code,mat.name,mat.model,(select IFNULL(sum(num),0) as num from inventory_record where inventoryMxId = mx.id and num > 0) as putIn",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "main.`time` desc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("orderForm", "detailId");
        $tr[]     = [$checkAll, '{l.inStockExec.addWaitPutIn.orderNo}', '{l.inStockExec.addWaitPutIn.code}', '{l.inStockExec.addWaitPutIn.materialName}', '{l.inStockExec.addWaitPutIn.model}', '{l.inStockExec.addWaitPutIn.notIn}'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "detailId", "value" => $array['id']),
            );
            $tr[]     = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['orderNum'] - $array['putIn'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='orderForm'>" .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'type', 'value' => $this->post('type'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 关联待入库单
     */
    public function addWaitPutInEdit()
    {
        $mxIdArr = $this->post('detailId');
        if (!$this->power(self::power, 'edit')) {
            $json['warn'] = L('inStockExec.addWaitPutInEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('inStockExec.addWaitPutInEdit.choice');
        } else {
            $tr = [];
            //是否自动生成批号
            //物料档案管理批号，并且公共设置批号自动生成，并且自动带出批号
            $inventorySetting = optionSettingClass::getSetting('库存');
            $optionSetting    = optionSettingClass::getSetting('公共');  //选项设置
            $batchCtrl        = $optionSetting['batchCtrl'];
            foreach ($mxIdArr as $detailId) {
                $inventory_detail = query("inventory_detail", " id = '" . $detailId . "' ");
                $inventory        = query("inventory", " id = '" . $inventory_detail['orderId'] . "' ", "orderNo");
                $material         = query('material', "id = '$inventory_detail[materialId]'");
                $batch            = $inventory_detail['batch'];
                if (empty($batch) && !empty($material['isBatch']) && $batchCtrl['auto'] && $inventorySetting['autoBatch']['option']) {
                    $batch = inStockClass::getBatchNo($this->post('type'), $this->post('targetId'));
                }
                $id                           = self::getId();
                $warehouseSel                 = idSelect(array(
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'change'   => 'getPosition',
                    'title'    => '仓库',
                    'value'    => $inventory_detail['warehouseId']
                ));
                $position                     = selectMultiple([
                    "name"     => "positionId[]",
                    'table'    => "warehouse_position",
                    'where'    => "coid = '" . self::$coid . "' and orderId = '" . $inventory_detail['warehouseId'] . "' and state = '启用' order by list",
                    'sqlId'    => 'id',
                    'sqlField' => 'name',
                    'value'    => $inventory_detail['positionId'] ?:
                        ($inventory_detail['warehouseId'] ? inventoryBalanceClass::matchLocation($inventory_detail['warehouseId']) : ''),
                    'title'    => L('inStockExec.edit.position')
                ]);
                $putIn                        = find(array(
                    'table'  => self::tableRecord,
                    'single' => "inventoryMxId = '$inventory_detail[id]'",
                    'field'  => " IFNULL(sum(num),0) as num "
                ));
                $notIn                        = $inventory_detail['orderNum'] - $putIn['num'];
                $inventory_detail['orderNum'] = self::lostZero($inventory_detail['orderNum'], 'numPrecision');
                $putIn['num']                 = self::lostZero($putIn['num'], 'numPrecision');
                $price                        = readOnlyInput(array("name" => "price[]", "value" => self::lostZero($inventory_detail['price'], 'pricePrecision')));
                $money                        = readOnlyInput(array("name" => "money[]", "value" => self::formattingFigure($notIn * $inventory_detail['price'])));
                $tr[]                         =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $material['id']]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => 'inventory_detail']) .
                        hidden(['name' => 'sourceId[]', 'value' => $detailId]),
                        $inventory['orderNo'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        $inventory_detail['orderNum'],
                        $putIn['num'],
                        $warehouseSel,
                        "<span class='position'>{$position}</span>",
                        text([
                            'name'  => 'num[]',
                            'blur'  => 'countMoney',
                            'value' => self::lostZero($notIn, 'numPrecision'),
                            'other' => self::digitalFiltering('numPrecision')
                        ]),
                        $price,
                        $money,
                        text(['name' => 'batch[]', 'value' => $batch]),
                    ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /**
     * @return string
     */
    public function addMx(): string
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = '';
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "type", "value" => $this->post('type')])
                . hidden(["name" => "targetId", "value" => $this->post('targetId')]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::power, 'edit')) {
            $json['warn'] = L('inStockExec.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('inStockExec.addMxEdit.choice');
        } else {
            $tr = [];
            //是否自动生成批号
            //物料档案管理批号，并且公共设置批号自动生成，并且自动带出批号
            $inventorySetting = optionSettingClass::getSetting('库存');
            $optionSetting    = optionSettingClass::getSetting('公共');  //选项设置
            $batchCtrl        = $optionSetting['batchCtrl'];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                if (!empty($material['isBatch']) && $batchCtrl['auto'] && $inventorySetting['autoBatch']['option']) {
                    $batch = inStockClass::getBatchNo($this->post('type'), $this->post('targetId'));
                } else {
                    $batch = "";
                }
                $id           = self::getId();
                $warehouseSel = idSelect(array(
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                    'sqlId'    => 'id',
                    'change'   => 'getPosition',
                    'sqlField' => "name",
                    'title'    => '仓库'
                ));
                $position     = selectMultiple([
                    "name"     => "positionId[]",
                    'table'    => "warehouse_position",
                    'where'    => "coid = '" . self::$coid . "' and orderId = '#' and state = '启用' order by list",
                    'sqlId'    => 'id',
                    'sqlField' => 'name',
                    'value'    => '',
                    'title'    => L('inStockExec.edit.position')
                ]);
                $price        = text(['name' => 'price[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision')]);
                $money        = text(['name' => 'money[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering()]);
                $tr[]       =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal();").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $mxId]) .
                        hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
                        hidden(['name' => 'sourceTable[]', 'value' => '']) .
                        hidden(['name' => 'sourceId[]', 'value' => '']),
                        '--',
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        '--',
                        '--',
                        $warehouseSel,
                        "<span class='position'>{$position}</span>",
                        text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => '', 'other' => self::digitalFiltering('numPrecision')]),
                        $price,
                        $money,
                        text(['name' => 'batch[]', 'value' => $batch])
                    ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}' ");
        if (empty($info['id'])) {
            $html = L('inStockExec.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            // 库存是否需要复核
            $checkCtrl = optionSettingClass::getSettingItem('库存', 'checkCtrl');
            $button    = [];
            if ($this->power(self::power, "edit") && ($info['state'] == '待入库' || ($info['state'] == '已入库' && $checkCtrl))) {
                /*if ($info['state'] == '待入库') {
                    //按钮
                    $button[] = [
                        "name" => L('inStockExec.detail.del'),
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }*/
                //按钮
                $button[] = [
                    "name"  => L('inStockExec.detail.edit'),
                    "type"  => "顶部页卡",
                    "title" => L('inStockExec.detail.editInfo'),
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                ];
            }
            if ($this->power(self::power, "edit") && $info['state'] == '待入库') {
                $button[] = [
                    "name"  => L('inStockExec.detail.sureIn'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::power, "check") && $info['state'] == '已入库' && $checkCtrl) {
                $button[] = [
                    "name" => L('inStockExec.detail.check'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'check', "id" => $info['id']],
                ];
            }
            if ($this->power(self::power, "print")) {
                //按钮
                $button[] = [
                    "name" => "打印",
                    "type" => "点击事件",
                    "fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[]   = ['单据来源', '{l.inStockExec.detail.sourceNo}', '{l.inStockExec.detail.code}', '{l.inStockExec.detail.name}', '{l.inStockExec.detail.model}', '{l.inStockExec.detail.unit}', '{l.inStockExec.detail.warehouse}', '{l.inStockExec.edit.position}', '{l.inStockExec.detail.orderNum}', '{l.inStockExec.detail.inNum}', '{l.inStockExec.detail.nowInNum}', '{l.inStockExec.edit.price}', '{l.inStockExec.detail.batch}'];
            $result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['orderNum'=>0,'putIn'=>0,'num'=>0];
            foreach ($result['array'] as $array) {
                $material  = query('material', " id = '$array[materialId]'");
                $warehouse = query('warehouse', " id = '$array[warehouseId]' ", 'name');
                $position  = query('warehouse_position', " id = '$array[positionId]' ", 'name');
                $sourceBut = '';
                if ($array['sourceId']) {
                    //追溯源单
                    $inventory_detail = query("inventory_detail", " id = '" . $array['sourceId'] . "' ", "sourceTable,sourceId,num");
                    $putIn['num']     = $inventory_detail['num'];
                    if ($inventory_detail['sourceTable'] == 'purchase_get_order_detail') {
                        $purchase_get_order_detail = query("purchase_get_order_detail", " id = '" . $inventory_detail['sourceId'] . "' ", "orderId,sourceId");
                        $purchase_order_detail     = query("purchase_order_detail", " id = '" . $purchase_get_order_detail['sourceId'] . "' ", "orderId");
                        if ($purchase_order_detail['orderId']) {
                            $sourceBut .= " <span class='del-row-button' onclick=\"newIframe('采购订单详情','" . root . "control/adIndex.html?cla=purchaseOrder&fun=detail&id=" . $purchase_order_detail['orderId'] . "')\">采购订单</span>";
                        }
                        if ($purchase_get_order_detail['orderId']) {
                            $sourceBut .= " <span class='del-row-button'  onclick=\"newIframe('采购收货单详情','" . root . "control/adIndex.html?cla=purchaseGetOrder&fun=detail&id=" . $purchase_get_order_detail['orderId'] . "')\">采购收货单</span>";
                        }
                    }
                } else {
                    $putIn['num'] = 0;
                }
                $price    = self::lostZero($array['price'], 'pricePrecision');
                $mxtr[]   = [
                    $sourceBut,
                    $array['sourceNo'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $warehouse['name'],
                    $position['name'],
                    self::lostZero($array['orderNum'], 'numPrecision'),
                    self::lostZero($putIn['num'], 'numPrecision'),
                    self::lostZero($array['num'], 'numPrecision'),
                    $price,
                    $array['batch'],
                ];
                $totalArr['orderNum'] += $array['orderNum'];
                $totalArr['putIn'] += $putIn['num'];
                $totalArr['num'] += $array['num'];
            }
            $total_tr = [
                8=>self::lostZero($totalArr['orderNum'], 'numPrecision'),
                9=>self::lostZero($totalArr['putIn'], 'numPrecision'),
                10=>self::lostZero($totalArr['num'], 'numPrecision'),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        L('inStockExec.detail.type')     => $info['type'],
                        L('inStockExec.detail.targetId') => $info['sourceTargetName'],
                        L('inStockExec.detail.orderNo') => $info['orderNo'],
                        L('inStockExec.detail.stid')    => self::findStaff($info['stid']),
                    ],
                    [
                        L('inStockExec.detail.state')   => $info['state'],
                    ],
                    [
                        L('inStockExec.detail.text') => pre($info['text']),
                    ],

                ]
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('inStockExec.detail.inMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'end' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id          = $this->post('id');
        $confirmTime = $this->post('confirmTime');
        $info        = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field       = [
            'state'       => '已入库',
            'confirmTime' => $confirmTime,
        ];
        if (!$this->power(self::power, 'edit')) {
            $json['warn'] = L('inStockExec.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('inStockExec.confirmEdit.empty');
        } elseif (empty($confirmTime)) {
            $json['warn'] = '请选择入库时间';
        } elseif ($info['state'] != '待入库') {
            $json['warn'] = L('inStockExec.confirmEdit.statusError');
        } else {
            $this->startTrans();
            $isPass = true; // 事务通过标志

            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                $details      = find([
                    'table' => self::tableMx,
                    'where' => " orderId = '{$info['id']}'",
                ]);
                $inStockLimit = optionSettingClass::getSettingItem('库存', 'inStockLimit');  // 入库数量允许超过源单数量
                foreach ($details['array'] as $key => $value) {
                    if ($value['num'] > 0) {
                        $material = query("material", " id = '" . $value['materialId'] . "' ");
                        // 转换主单位
                        $mainUnitNum = machiningOrderClass::material_num_change($material['id'], $value['unit'], $material['unit'], $value['num']);
                        //源单数据
                        $inventory_detail = ['orderId' => '', 'id' => ''];
                        if ($value['sourceId']) {
                            $inventory_detail = query("inventory_detail", " id = '$value[sourceId]' ");
                            $inventory        = query("inventory", " id = '$inventory_detail[orderId]' ");
                            //处理源单关联逻辑
                            $detailMoney = ($inventory_detail['num'] + $value['num']) * $inventory_detail['price'] * (1 + $inventory_detail['rate']);
                            $nowNum      = $inventory_detail['num'] + $value['num'];
//                            if (!$inStockLimit && $nowNum > $inventory_detail['orderNum'] && $inventory_detail['orderNum'] > 0) {
//                                $json['warn'] = "【" . $material['name'] . "】入库数量不允许超过源单数量,源单剩余未入库数量【" . ($inventory_detail['orderNum'] - $inventory_detail['num']) . "】";
//                                goto resp;
//                            }
                            $json['warn'] = static::update([
                                "table" => 'inventory_detail',
                                "field" => [
                                    'num'   => $nowNum,
                                    'money' => $detailMoney,
                                ],
                                "where" => "id = '$inventory_detail[id]'",
                            ]);
                            if (!in_array($json['warn'], ["新增成功", "更新成功"])) {
                                goto resp;
                            }
                            //如果是生产退料且未关联任何单单据或者关联的是领料单中未关联单据的，生成线边库存出库记录
                            if ($inventory['type'] == '生产退料') {
                                $pick_order_detail = query('pick_order_detail', "id = '$inventory_detail[sourceId]'");
                                if (empty($pick_order_detail['sourceId'])) {
                                    $bool = tempInventoryClass::insertRecord(array(
                                        'lineId'        => $inventory['targetId'],
                                        'materialId'    => $inventory_detail['materialId'],
                                        'inventoryId'   => $inventory['id'],
                                        'inventoryMxId' => $inventory_detail['id'],
                                        'num'           => -$mainUnitNum,
                                        'text'          => '生产退料',
                                        'changesId'     => $value['id'],
                                    ));
                                    if ($bool !== true) {
                                        $json['warn'] = $bool;
                                        goto resp;
                                    }
                                } else {
                                    //关联了领料单，但领料单未关联任何单据的
                                    $pick_order_detail = query('pick_order_detail', "id = '$pick_order_detail[sourceId]'");
                                    if (empty($pick_order_detail['sourceId'])) {
                                        $bool = tempInventoryClass::insertRecord(array(
                                            'lineId'        => $inventory['targetId'],
                                            'materialId'    => $inventory_detail['materialId'],
                                            'inventoryId'   => $inventory['id'],
                                            'inventoryMxId' => $inventory_detail['id'],
                                            'num'           => -$mainUnitNum,
                                            'text'          => '生产退料',
                                            'changesId'     => $value['id'],
                                        ));
                                        if ($bool !== true) {
                                            $json['warn'] = $bool;
                                            goto resp;
                                        }
                                    }
                                }
                            }
                            //线边库存退库，需要扣减线边库存
                            if ($inventory['type'] == '线边库存退库') {
                                $bool = tempInventoryClass::insertRecord(array(
                                    'lineId'        => $inventory['targetId'],
                                    'materialId'    => $inventory_detail['materialId'],
                                    'inventoryId'   => $inventory['id'],
                                    'inventoryMxId' => $inventory_detail['id'],
                                    'num'           => -$mainUnitNum,
                                    'text'          => '线边库存退库',
                                    'changesId'     => $value['id'],
                                ));
                                if ($bool !== true) {
                                    $json['warn'] = $bool;
                                    goto resp;
                                }
                            }
                            // 关联表
                            $targetDate = $targetNo = $targetText = $hiddenText = ' ';
                            if ($inventory['sourceTable']) {
                                $obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
                                if (!empty($obj['id'])) {
                                    $targetDate = $obj['recordDate'];
                                    $targetNo   = $obj['orderNo'];
                                    $targetText = $inventory['type'] . "单【{$obj['orderNo']}】";
                                    $hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，入库单ID：' . $inventory_detail['orderId'] . '入库单子ID：' . $inventory_detail['id'];
                                }
                            }
                            $bool = supplierClass::insertRecord(
                                $inventory['targetId'],
                                $inventory['type'],
                                self::formattingFigure($value['num'] * $inventory_detail['price'] * (1 + $inventory_detail['rate'])),
                                'inventory_detail',
                                $inventory_detail['id'],
                                $targetDate== ' ' ? date("Y-m-d H:i:s") : $targetDate,
                                $targetNo,
                                $targetText,
                                $hiddenText,
                                $value['id']
                            );
                            if ($bool !== true) {
                                $json['warn'] = $bool;
                                goto resp;
                            }
                            //修改待入库单状态
                            $notIn = find(array(
                                'table'  => 'inventory_detail',
                                'single' => "orderId = '$inventory[id]' and num < orderNum and coid = '" . self::$coid . "' and id <> '" . $inventory_detail['id'] . "'",
                                'field'  => " IFNULL(count(id),0) as num "
                            ));
                            if ($nowNum >= $inventory_detail['orderNum'] && $notIn['num'] == 0) {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'       => '已入库',
                                        'confirmTime' => $confirmTime,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            } elseif ($inventory['state'] == '待入库') {
                                static::update([
                                    'table' => 'inventory',
                                    'field' => [
                                        'state'      => '部分入库',
                                        'commitTime' => $confirmTime,
                                    ],
                                    'where' => " id = '{$inventory['id']}' ",
                                ]);
                            }
                        }
                        //检查物料的入库批次是否使用过
                        $warn = inStockClass::batchCheck($value['materialId'], [$value['batch']]);
                        if ($warn !== true) {
                            $json['warn'] = $warn;
                            goto resp;
                        }
                        $warn = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "top");  //最高库存控制
                        if ($warn !== true) {
                            $json['warn'] = $warn;
                            goto resp;
                        }
                        if ($value['positionId']) {
                            $material['positionId'] = $value['positionId'];
                            $material['warehouse']  = $value['warehouseId'];
                        } elseif (empty($material['positionId']) || $material['warehouse'] != $value['warehouseId']) {
                            $material['positionId'] = inventoryBalanceClass::matchLocation($value['warehouseId']);
                            $material['warehouse']  = $value['warehouseId'];
                        }
                        //单位单价转换
                        $price = self::formattingFigure((float)$value['num'] * (float)$value['price'] / (float)$mainUnitNum, 'pricePrecision');
//                        inventoryDefaultClass::recordInventoryPrice($value['materialId'], $mainUnitNum, $price);//计算记录加权平均单价
                        $recordId = self::getNo();
                        static::insert([
                            'table' => self::tableRecord,
                            'field' => [
                                'id'            => $recordId,
                                'coid'          => self::$coid,
                                'warehouseId'   => $material['warehouse'],
                                'positionId'    => $material['positionId'],
                                'materialId'    => $value['materialId'],
                                'batch'         => $value['batch'],
                                'num'           => $mainUnitNum,
                                'inventoryId'   => $inventory_detail['orderId'],
                                'inventoryMxId' => $inventory_detail['id'],
                                'changesId'     => $value['id'],
                                'defaultPrice'  => $price,
                                'time'          => $confirmTime,
                            ],
                        ]);
                        if (!empty($material['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $material['positionId']]);
                    }
                }
                $this->commitTrans();//提交事务
                auditingFollow(array(
                    "type"   => "入库单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('inStockExec.confirmEdit.log'));
                $this->logText(["type" => self::printPage, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 复核
     */
    public function checkEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state'      => '已复核',
            'reviewTime' => $this->time,
        ];
        if (!$this->power(self::power, 'check')) {
            $json['warn'] = L('inStockExec.checkEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('inStockExec.checkEdit.empty');
        } elseif ($info['state'] != '已入库') {
            $json['warn'] = L('inStockExec.checkEdit.statusError');
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow([
                    "type"   => "入库单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】复核",
                ]);

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('inStockExec.checkEdit.log'));
                $this->logText(["type" => self::printPage, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act    = $this->post('act') ?? '';
        $pwd    = $word = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'confirm':
                $act      = 'edit';
                $msg      = L('inStockExec.operate.confirm');
                $title    = L('inStockExec.operate.confirmTitle');
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                $append   = [
                    must . '入库时间：' => text([
                            "name"    => "confirmTime",
                            "title"   => "入库时间",
                            "value"   => $this->time,
                            'laydate' => ['type' => 'datetime'],
                        ]) . space,
                ];
                break;
            case 'check':
                $act      = 'check';
                $msg      = L('inStockExec.operate.check');
                $title    = L('inStockExec.operate.checkTitle');
                $function = 'checkEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'cancel': //作废
                $act      = 'cancel';
                $msg      = L('inStockExec.operate.cancel');
                $title    = L('inStockExec.operate.cancelTitle');
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, listForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'updateTime':
                $act      = 'edit';
                $msg      = '修改入库完成时间';
                $title    = '';
                $function = 'updateTime';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word     = true;
                $append   = [
                    [
                        must . '上班时间：' => text(["name" => "startTime", "laydate" => ['type' => 'time'], "title" => "上班时间", 'value' => '09:00:00']) . "-\n" .
                            text(["name" => "endTime", "laydate" => ['type' => 'time'], "title" => "下班时间", 'value' => '18:00:00'])
                    ],
                    [
                        must . '当前入库完成时间段：' => text(["name" => "nowStart", "laydate" => [], "title" => "当前入库完成时间段开始"]) . "-\n" .
                            text(["name" => "nowEnd", "laydate" => [], "title" => "当前入库完成时间段结束"])
                    ],
                    [
                        must . '期望入库完成时间段：' => text(["name" => "expectStart", "laydate" => [], "title" => "期望入库完成时间段开始"]) . "-\n" .
                            text(["name" => "expectEnd", "laydate" => [], "title" => "期望入库完成时间段结束"])
                    ]
                ];
                break;
            default:
                $act      = 'del';
                $msg      = L('inStockExec.operate.delMsg');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::power, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('inStockExec.operate.log'));
            $json             = [
                'warn' => 2,
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'append'   => $append,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改销售成本(inventory_detail_changes的单价)
     */
    public function changeCost($data)
    {
        $where        = self::timeComparison($data['nowStart'] . '~' . $data['nowEnd'], 'date', 'recordDate');
        $saleOrderAll = find(['table' => 'sale_order', 'where' => "state = '已确认' {$where} order by orderNo asc"]);
        foreach ($saleOrderAll['array'] as $saleOrder) {
            $all = find(['table' => 'sale_order_detail', 'where' => "orderId = '$saleOrder[id]'"]);
            foreach ($all['array'] as $array) {
                $mxAll = find(['table' => 'sale_send_order_detail', 'where' => "saleOrderMxId = '$array[id]'"]);
                foreach ($mxAll['array'] as $mx) {
                    $inventoryDetailAll = find(['table' => 'inventory_detail', 'where' => "sourceId = '$mx[id]'"]);
                    foreach ($inventoryDetailAll['array'] as $inventoryDetail) {
                        $inventoryChangeDetailAll = find(['table' => 'inventory_changes_detail', 'where' => "sourceId = '$inventoryDetail[id]'"]);
                        foreach ($inventoryChangeDetailAll['array'] as $inventoryChangeDetail) {
                            $price = $this->priceRand($mx['price'] * (1 + $mx['rate']), $data['expectStart'], $data['expectEnd']);
                            self::update(['table' => 'inventory_changes_detail', 'field' => ['price' => $price, 'money' => self::formattingFigure($price * $inventoryChangeDetail['num'])], 'where' => "id = '$inventoryChangeDetail[id]'"]);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取一个随机单价(再指定范围的百分比之间)
     * @param $price
     * @param int $min
     * @param int $max
     * @return mixed
     */
    public function priceRand($price, $min = 0, $max = 100)
    {
        return self::formattingFigure($price * ((mt_rand($min, $max) / 100)), 'pricePrecision');
    }

    /**
     * 修改入库完成时间
     */
    public function updateTime()
    {
        $field      = [
            'startTime'   => $this->post('startTime'),
            'endTime'     => $this->post('endTime'),
            'nowStart'    => $this->post('nowStart'),
            'nowEnd'      => $this->post('nowEnd'),
            'expectStart' => $this->post('expectStart'),
            'expectEnd'   => $this->post('expectEnd'),
        ];
        $annotation = [
            'startTime'   => '上班时间',
            'endTime'     => '下班时间',
            'nowStart'    => '当前入库完成时间段开始',
            'nowEnd'      => '当前入库完成时间段结束',
            'expectStart' => '期望入库完成时间段开始',
            'expectEnd'   => '期望入库完成时间段结束',
        ];
        $rules      = [
            'startTime'   => 'required',
            'endTime'     => 'required',
            'nowStart'    => 'required|date',
            'nowEnd'      => 'required|date',
            'expectStart' => 'required',
            'expectEnd'   => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            return json_encode(['warn' => $vt->getErrs()[0]], 320);
        }
        if ($this->post('startTime') == 3 && $this->post('endTime') == 4) {
            $this->changeCost($field);
            return json_encode(['warn' => '操作成功'], 320);
        }
        if ($this->post('startTime') == 1 && $this->post('endTime') == 2) {
            $mx = find(array('table' => 'inventory', 'where' => " coid = '" . self::$coid . "' and type in ('销售退货','采购退货') and sourceDate is not null "));
            foreach ($mx['array'] as $value) {
                if ($value['classify'] == 0) {
                    $orderNo = codeTemplateClass::generateCode('outStock', [
                        'prefix' => 'KCCK' . date('Ymd', strtotime($value['sourceDate'])),
                        'table'  => 'inventory',
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ], $value);
                } else {
                    $orderNo = codeTemplateClass::generateCode('inStock', [
                        'prefix' => 'KCRK' . date('Ymd', strtotime($value['sourceDate'])),
                        'table'  => 'inventory',
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ], $value);
                }
                $bool = sqlExec(" UPDATE inventory SET orderNo = '$orderNo',updateTime = `updateTime` WHERE id = '$value[id]' ");
            }
            $mx = find(array('table' => self::table, 'where' => " coid = '" . self::$coid . "' and type in ('生产入库','销售退货','生产领料','采购退货') and confirmTime is not null "));
            foreach ($mx['array'] as $value) {
                $confirmTime = $value['confirmTime'];
                if ($value['classify'] == 0) {
                    $orderNo = codeTemplateClass::generateCode('outStock', [
                        'prefix' => 'CKD' . date('Ymd', strtotime($value['confirmTime'])),
                        'table'  => self::table,
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ], $value);
                } else {
                    $orderNo = codeTemplateClass::generateCode('inStock', [
                        'prefix' => 'RKD' . date('Ymd', strtotime($value['confirmTime'])),
                        'table'  => self::table,
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ], $value);
                }
                $bool = sqlExec(" UPDATE " . self::table . " SET orderNo = '$orderNo',updateTime = `updateTime` WHERE id = '$value[id]' ");
                /*
                //修改源数据创建时间
                if($value['classify'] == 0){
                    //修改客户
                    $target = query("kehu", " khid = '$value[targetId]' ", "khid,updateTime,time");
                    if(strtotime($confirmTime) < strtotime($target['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'kehu',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " khid = '$target[khid]' ",
                        ));
                    }
                }else{
                    //修改供应商
                    $target = query("supplier", " id = '$value[targetId]' ", "id,updateTime,time");
                    if(strtotime($confirmTime) < strtotime($target['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'supplier',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$target[id]' ",
                        ));
                    }
                }
                $res = find(array(
                    'table' => self::tableMx,
                    'field' => 'id,sourceId,materialId,warehouseId,positionId',
                    'where' => " coid = '".self::$coid."' and orderId = '$value[id]' "
                ));
                foreach ($res['array'] as $arr) {
                    //修改带出入库单
                    if($arr['sourceId']) {
                        $inventory_detail = query("inventory_detail", " id = '$arr[sourceId]' ", "orderId");
                        $inventory = query("inventory", " id = '$inventory_detail[orderId]' ", "sourceDate");
                        if($inventory['sourceDate']) {
                            $time = $inventory['sourceDate'] . ' ' . date("H:i:s", mt_rand(strtotime('09:00:00'), strtotime('18:00:00')));
                            update(array(
                                "table" => 'inventory',
                                "field" => [
                                    'orderNo'    => codeTemplateClass::generateCode(self::power, [
                                        'prefix' => 'RKD' . date('Ymd', strtotime($inventory['sourceDate'])),
                                        'table'  => 'inventory',
                                        'field'  => 'orderNo',
                                        'where'  => " AND coid = '" . self::$coid . "' ",
                                    ], $inventory),
                                    'orderDate'  => $inventory['sourceDate'],
                                    'updateTime' => $time,
                                    'time'       => $time,
                                ],
                                "where" => " id = '$inventory_detail[orderId]' ",
                            ));
                        }
                    }
                    //修改物料
                    $material = query("material", " id = '$arr[materialId]' ", "id,updateTime,time");
                    if(strtotime($confirmTime) < strtotime($material['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'material',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$material[id]' ",
                        ));
                    }
                    //修改仓库
                    $warehouse = query("warehouse", " id = '$arr[warehouseId]' ", "id,updateTime,time");
                    if(strtotime($confirmTime) < strtotime($warehouse['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'warehouse',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$warehouse[id]' ",
                        ));
                    }
                    //修改库位
                    $warehouse_position = query("warehouse_position", " id = '$arr[positionId]' ", "id,updateTime,time");
                    if(strtotime($confirmTime) < strtotime($warehouse_position['time'])) {
                        $advanceMinutes = mt_rand(20, 60);
                        $time = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                        update(array(
                            "table" => 'warehouse_position',
                            "field" => ['updateTime' => $time, 'time' => $time],
                            "where" => " id = '$warehouse_position[id]' ",
                        ));
                    }
                }*/
            }
            return json_encode(['warn' => '操作成功'], 320);
        } else {
            $field      = [
                'startTime'   => $this->post('startTime'),
                'endTime'     => $this->post('endTime'),
                'nowStart'    => $this->post('nowStart'),
                'nowEnd'      => $this->post('nowEnd'),
                'expectStart' => $this->post('expectStart'),
                'expectEnd'   => $this->post('expectEnd'),
            ];
            $annotation = [
                'startTime'   => '上班时间',
                'endTime'     => '下班时间',
                'nowStart'    => '当前入库完成时间段开始',
                'nowEnd'      => '当前入库完成时间段结束',
                'expectStart' => '期望入库完成时间段开始',
                'expectEnd'   => '期望入库完成时间段结束',
            ];
            $rules      = [
                'startTime'   => 'required',
                'endTime'     => 'required',
                'nowStart'    => 'required|date',
                'nowEnd'      => 'required|date',
                'expectStart' => 'required|date',
                'expectEnd'   => 'required|date',
            ];
            // 校验是否符合规则
            $vt     = new \verify();
            $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
            if ($result === false) {
                $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            } else {
                $where = self::timeComparison($field['nowStart'] . '~' . $field['nowEnd'], 'date', 'confirmTime');
                $mx    = find(array('table' => self::table, 'where' => " coid = '" . self::$coid . "' and classify = 1 and confirmTime is not null {$where}"));
                foreach ($mx['array'] as $value) {
                    $confirmTime = date('Y-m-d', mt_rand(strtotime($field['expectStart']), strtotime($field['expectEnd']))) . ' ' . date('H:i:s', mt_rand(strtotime($field['startTime']), strtotime($field['endTime'])));
                    $orderNo     = codeTemplateClass::generateCode(self::power, [
                        'prefix' => 'RKD' . date('Ymd', strtotime($confirmTime)),
                        'table'  => self::table,
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ], $value);
                    update(array(
                        "table" => self::table,
                        "field" => ['orderNo' => $orderNo, 'confirmTime' => $confirmTime],
                        "where" => "id = '$value[id]'",
                    ));
                    //修改供应商
                    if ($value['targetId']) {
                        $target = query("supplier", " id = '$value[targetId]' ", "id,updateTime,time");
                        if (strtotime($confirmTime) < strtotime($target['time'])) {
                            $advanceMinutes = mt_rand(20, 60);
                            $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                            update(array(
                                "table" => 'supplier',
                                "field" => ['updateTime' => $time, 'time' => $time],
                                "where" => " id = '$target[id]' ",
                            ));
                        }
                    }
                    $res = find(array(
                        'table' => self::tableMx,
                        'field' => 'id,sourceId,materialId,arehouseId,positionId',
                        'where' => " coid = '" . self::$coid . "' and orderId = '$value[id]' "
                    ));
                    foreach ($res['array'] as $arr) {
                        update(array(
                            "table" => 'inventory_record',
                            "field" => ['time' => $confirmTime],
                            "where" => " changesId = '$arr[id]' ",
                        ));
                        //修改带出入库单
                        if ($arr['sourceId']) {
                            $inventory_detail = query("inventory_detail", " id = '$arr[sourceId]' ", "orderId");
                            $inventory        = query("inventory", " id = '$inventory_detail[orderId]' ", "sourceDate");
                            if ($inventory['sourceDate']) {
                                $time = $inventory['sourceDate'] . ' ' . date("H:i:s", mt_rand(strtotime('09:00:00'), strtotime('18:00:00')));
                                update(array(
                                    "table" => 'inventory',
                                    "field" => [
                                        'orderNo'    => codeTemplateClass::generateCode(self::power, [
                                            'prefix' => 'RKD' . date('Ymd', strtotime($inventory['sourceDate'])),
                                            'table'  => 'inventory',
                                            'field'  => 'orderNo',
                                            'where'  => " AND coid = '" . self::$coid . "' ",
                                        ], $inventory),
                                        'orderDate'  => $inventory['sourceDate'],
                                        'updateTime' => $time,
                                        'time'       => $time,
                                    ],
                                    "where" => " id = '$inventory_detail[orderId]' ",
                                ));
                            }
                        }
                        //修改物料
                        $material = query("material", " id = '$arr[materialId]' ", "id,updateTime,time");
                        if (strtotime($confirmTime) < strtotime($material['time'])) {
                            $advanceMinutes = mt_rand(20, 60);
                            $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                            update(array(
                                "table" => 'material',
                                "field" => ['updateTime' => $time, 'time' => $time],
                                "where" => " id = '$material[id]' ",
                            ));
                        }
                        //修改仓库
                        $warehouse = query("warehouse", " id = '$arr[warehouseId]' ", "id,updateTime,time");
                        if (strtotime($confirmTime) < strtotime($warehouse['time'])) {
                            $advanceMinutes = mt_rand(20, 60);
                            $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                            update(array(
                                "table" => 'warehouse',
                                "field" => ['updateTime' => $time, 'time' => $time],
                                "where" => " id = '$warehouse[id]' ",
                            ));
                        }
                        //修改库位
                        $warehouse_position = query("warehouse_position", " id = '$arr[positionId]' ", "id,updateTime,time");
                        if (strtotime($confirmTime) < strtotime($warehouse_position['time'])) {
                            $advanceMinutes = mt_rand(20, 60);
                            $time           = date('Y-m-d H:i:s', strtotime("$confirmTime -{$advanceMinutes} minute"));
                            update(array(
                                "table" => 'warehouse_position',
                                "field" => ['updateTime' => $time, 'time' => $time],
                                "where" => " id = '$warehouse_position[id]' ",
                            ));
                        }
                    }

                }
                //返回
                $_SESSION['warn'] = '操作成功';
                $json['warn']     = 2;
            }
            resp:
            return json_encode($json, 320);
        }
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::power, "del")) {
            $json['warn'] = L('inStockExec.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('inStockExec.delete.none');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] == '已复核') {
                    $warn = L('inStockExec.delete.fail');
                } elseif ($info['state'] == '已入库' && sqlNum(self::tableMx, " (coid = '" . self::$coid . "' AND orderId = '{$id}') AND num > 0   ") > 0) {
                    $warn = L('inStockExec.delete.numFail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('inStockExec.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], lang('inStockExec.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('inStockExec.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::printPage, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('inStockExec.delete.warn'));
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array  = explode(',', $listId);
            $data   = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::power, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id                  = $param ?: $this->get('id');
        $info                = query(self::table, " id = '{$id}'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称
        $info['title']       = self::title;
        $info['printTime']   = $this->time;
        $info['stid']        = self::findStaff($info['stid']);
        $info['targetId']    = self::getCompanyName($info['targetId']);
        $info['qr']          = 'source=' . self::printPage . 'Other&id=' . $info['id'];
        $info['orderDate']   = date('Y/m/d', strtotime($info['time']));
        $detail              = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items               = [];
        $x                   = 1;
        $totalNum            = $totalMoney = 0;
        foreach ($detail as $array) {
            $material  = query('material', "id = '$array[materialId]'");
            $warehouse = query('warehouse', "id = '$array[warehouseId]'");
            $items[]   = [
                'no'           => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'warehouse'    => $warehouse['name'],
                'model'        => $material['model'],
                'unit'         => $array['unit'],
                'batch'        => $array['batch'],
                'num'          => self::lostZero($array['num'], 'numPrecision'),
                'price'        => self::lostZero($array['price'], 'pricePrecision'),
                'money'        => static::formattingFigure($array['num'] * $array['price']),
            ];
            $x++;
            $totalNum   += floatval($array['num']);
            $totalMoney += static::formattingFigure($array['num'] * $array['price']);
        }
        $append         = [
            'no'    => L('inStockExec.printPage.total'),
            'num'   => self::lostZero($totalNum, 'numPrecision'),
            'money' => static::lostZero($totalMoney),
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(static::printPage, $info, '入库');
        } else {
            return $info;
        }
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'往来单位编号',
                    'aliasName'=>'往来单位编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'往来单位名称',
                    'aliasName'=>'往来单位名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据备注',
                    'aliasName'=>'单据备注',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'待入库单号',
                    'aliasName'=>'待入库单号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'仓库编码',
                    'aliasName'=>'仓库编码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'库位编码',
                    'aliasName'=>'库位编码',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'库位名称',
                    'aliasName'=>'库位名称',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'入库完成时间',
                    'aliasName'=>'入库完成时间',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
                [
                    'columnName'=>'待入库单号',
                    'aliasName'=>'待入库单号',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'库位',
                    'aliasName'=>'库位',
                ],
                [
                    'columnName'=>'单据数量',
                    'aliasName'=>'单据数量',
                ],
                [
                    'columnName'=>'已入库数量',
                    'aliasName'=>'已入库数量',
                ],
                [
                    'columnName'=>'本次入库数量',
                    'aliasName'=>'本次入库数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',
                ],
                [
                    'columnName'=>'批号',
                    'aliasName'=>'批号',
                ],
            ]
        };
    }
}
